using System;
using IValidate;
using System.Collections.Generic;
using System.Reflection;

namespace IValidate
{
	public static class Model
	{
		public static bool IsValid(object model)
		{
			return new List<string>(GetErrorMessages(model)).Count == 0;
		}
		public static IEnumerable<string> GetErrorMessages(object model)
		{
			List<string> result = new List<string>();
			if (model == null)
				return result;

			foreach (PropertyInfo prop in model.GetType().GetProperties())
			{
				IModelValidator[] validators = GetValidators(prop);
				if (validators == null)
					continue;

				foreach (IModelValidator validator in validators)
				{
					if (!validator.Validate(prop.GetValue(model, null)))
						result.Add(validator.ErrorMessage);
				}
			}
			return result;
		}
		private static IModelValidator[] GetValidators(PropertyInfo prop)
		{
			object[] attribs = prop.GetCustomAttributes(typeof(IModelValidator), true);
			IModelValidator[] validators = null;
			if (attribs != null && attribs.Length > 0)
			{
				validators = Array.ConvertAll<object, IModelValidator>(attribs,
					obj =>
					{
						return obj as IModelValidator;
					}
				);
			}
			return validators;
		}
	}
}
